package servlet;

import user.ShopCar;
import util.DBUtilDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class UpdateShopCarServlet extends HttpServlet { //添加购物车
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String) request.getSession().getAttribute("username");
        if (username == null) {
            response.getWriter().println("请先登录！！！（2秒后自动跳转）");
            response.setHeader("refresh", "2;URL=login.jsp");
        } else {
            DBUtilDao dbUtilDao = new DBUtilDao();
            String phoneNumber = (String) request.getSession().getAttribute("username");
            String fruit = request.getParameter("fruit");
            ShopCar shopCar = null;
            if (fruit.equals("orange")) {
                float pirce= (float) request.getSession().getAttribute("orange");//获取橘子价格
                shopCar = new ShopCar(phoneNumber, 1, pirce, "orange");
            } else if (fruit.equals("apple")) {
                float pirce= (float) request.getSession().getAttribute("apple");//获取苹果价格
                shopCar = new ShopCar(phoneNumber, 1, pirce, "apple");
            }
            try {
                dbUtilDao.updateShopCar(shopCar); //更新数据库中的购物车
                dbUtilDao.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            SelectShopCarServlet selectShopCarServlet = new SelectShopCarServlet();
            selectShopCarServlet.doGet(request, response); //刷新购物车的页面
            response.sendRedirect("shopcar.jsp");
        }

    }
}
